<?php
namespace lib\rpc;
use config\config;
use lib\helper\error;
use lib\redis\RedisTool;

class RpcClient {

    private static $sendData;
    private static $service;
    private static $action;
    private static $args;
    private static $rpcTool;


    public static function find($service){
        if (!self::$rpcTool){
            self::$rpcTool = new RpcClient();
        }
        self::$service = $service;
        return self::$rpcTool;
    }

    public function __call($name, $arguments)
    {
        self::$action = $action = $name;
        self::$args = $args = $arguments;
        $service = self::$service;
        self::$sendData = json_encode(compact('service','action','args'));
        return $this->send();
    }

    private function send(){
        $node = config::get('rpc');
        $fp = stream_socket_client("tcp://{$node['ip']}:{$node['port']}");
        fwrite($fp, self::$sendData );
        $data = json_decode(fread($fp, 65533),true);
        if ($data['code'] == 400){
            error::_plainError(['message'=>$data['message']],false);
        }
        if(empty($data)){
            $data= ['code'=>400,'message'=>'RPC异常,请重启supervisor rpcTask'];
            error::_plainError(['message'=>$data['message']],false,'http://task.lidongyu.cn');
        }
        return $data['data'];
    }
}
